<template>
  <div class="login-wrapper">
    <div class="modal">
      <el-form :model="user" :rules="rules" ref="userFormRef">
        <div class="title">梦开始的地方</div>
        <el-form-item prop="userName">
          <el-input v-model="user.userName" />
        </el-form-item>
        <el-form-item prop="userPwd">
          <el-input v-model="user.userPwd" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" class="btn" @click="login(userFormRef)"
            >登录</el-button
          >
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { useStore } from 'vuex'
import api from './../api'
// getCurrentInstance vue 全局的api  获取vue所有上下文的信息
import { ref, reactive, getCurrentInstance } from 'vue'
// const { proxy } = getCurrentInstance()
// proxy 劫持对象  可以找到$api proxy.$api.login() 可以发请求
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
// import type { Action } from 'element-plus'
let router = useRouter()
let user = reactive({ userName: '', userPwd: "" })
let store = useStore()

let rules = reactive({
  userName: [
    {
      //   required: true,
      message: '请输入用户名',
      trigger: 'blur'
    }
  ],
  userPwd: [
    {
      //   required: true,
      message: '请输入密码',
      trigger: 'blur'
    }
  ]
})

let userFormRef = ref(null)

const login = (formRef) => {
  console.log(formRef);
  formRef.validate((vaild) => {
    console.log(vaild);
    // 该变量根据刚刚设置rules去匹配，都满足则返回true，不满足则返回false
    if (vaild) {
      //   console.log(proxy);
      api.login(user)
        .then((userInfo) => {
          console.log(userInfo);
          store.commit('saveUserInfo', userInfo)
          router.push('/')
          ElMessage({
            message: '登录成功',
            type: 'success',
          })
        })
      // 发送请求 并获取token 然后保存 跳转到首页
      // token 保存到vuex中
    }
  })
}
</script>

<style lang="scss" scoped>
.login-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100vh;
  background-color: white;

  .modal {
    width: 500px;
    background-color: white;
    border-radius: 20px;
    padding: 50px;
    box-shadow: 0 0 10px 3px #ddd;

    .title {
      text-align: center;
      font-size: 50px;
      margin-bottom: 30px;
      line-height: 1.5;
    }
    .btn {
      width: 100%;
    }
  }
}
</style>